import subprocess
import logging
from util import validate_file_path

# 设置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def run_ffmpeg_command(command):
    """运行FFmpeg命令"""
    try:
        logging.info(f"Running command: {command}")
        subprocess.run(command, check=True, shell=True)
    except subprocess.CalledProcessError as e:
        logging.error(f"FFmpeg command failed: {e}")
    except Exception as e:
        logging.error(f"An error occurred: {e}")

def convert_video_format(input_file, output_file, output_format):
    """转换视频格式"""
    if not validate_file_path(input_file):
        return
    if not output_file or not output_format:
        logging.error("Invalid input parameters")
        return
    command = f"ffmpeg -i {input_file} {output_file}.{output_format}"
    run_ffmpeg_command(command)

def extract_audio(input_file, output_file):
    """提取音频"""
    if not validate_file_path(input_file):
        return
    if not output_file:
        logging.error("Invalid input parameters")
        return
    command = f"ffmpeg -i {input_file} -q:a 0 -map a {output_file}.mp3"
    run_ffmpeg_command(command)

def create_video_thumbnail(input_file, output_image, time="00:00:01"):
    """创建视频缩略图"""
    if not validate_file_path(input_file):
        return
    if not output_image:
        logging.error("Invalid input parameters")
        return
    command = f"ffmpeg -i {input_file} -ss {time} -vframes 1 {output_image}.png"
    run_ffmpeg_command(command)

def resize_video(input_file, output_file, width, height):
    """调整视频大小"""
    if not validate_file_path(input_file):
        return
    if not output_file or width <= 0 or height <= 0:
        logging.error("Invalid input parameters")
        return
    command = f"ffmpeg -i {input_file} -vf scale={width}:{height} {output_file}"
    run_ffmpeg_command(command)